#include <stdio.h>
#include <lcthw/linear_list.h>
#include <stdlib.h>

SqList *InitList()
{
    SqList *L = (SqList *)malloc(sizeof(SqList));
    printf("InitList: %p\n", L);
    if (!L)
    {
        printf("InitList: malloc failed\n");
        return NULL;
    }
    L->length = 0;
    return L;
}

int ListTraverse(SqList *L, List_traverse_cb traverse_cb)
{
    for (int i = 0; i < L->length; i++)
    {
        printf("The %dth element is: ", i + 1);
        traverse_cb(&L->data[i]);
    }
    return 0;
}

/*
void ClearList(SqList *L,myfunc cell_method)
{
    int SIZE = L->length;
    ListTraverse(L, SIZE, cell_method);
    L->length = 0;
}*/

void DestroyList(SqList *L)
{
 //   ClearList(L, cell_method);
    free(L);
}

int ListEmpty(SqList *L)
{
    if(L->length == 0)
        return 0;
    else
        return 1;
}

int ListInsert(SqList *L, int i, int e)
{
    if (i < 1 || i > L->length + 1)
    {
        printf("ListInsert: i is out of range\n");
        return -1;
    }
    if (L->length >= MAXSIZE)
    {
        printf("ListInsert: list is full\n");
        return -1;
    }
    if(ListEmpty(L) == 0)
    {
        L->data[0] = e;
        L->length++;
        return 0;
    }
    if(i<=L->length)
    {
        for (int j = L->length - 1; j >= i - 1; j--)
        {
            L->data[j + 1] = L->data[j];
        }
    }
    L->data[i - 1] = e;
    L->length++;
    return 0;
}

int ListDelete(SqList *L, int i, int *e)
{
    if (i < 1 || i > L->length)
    {
        printf("ListDelete: i is out of range\n");
        return -1;
    }
    *e = L->data[i - 1];
    for (int j = i; j < L->length; j++)
    {
        L->data[j - 1] = L->data[j];
    }
    L->length--;
    return 0;
}

int ListLength(SqList *L)
{
    return L->length;
}

int GetElem(SqList *L, int i, int *e)
{
    int status = ListEmpty(L);
    if (status == 0)
    {
        printf("GetElem: list is empty\n");
        return -1;
    }

    if (i < 1 || i > L->length)
    {
        printf("GetElem: i is out of range\n");
        return -1;
    }

    *e = L->data[i - 1];

    return 0;
}

int LocateElem(SqList *L, int e)
{
    int status = ListEmpty(L);
    if (status == 0)
    {
        printf("LocateElem: list is empty\n");
        return -1;
    }

    for (int i = 0; i < L->length; i++)
    {
        if (L->data[i] == e)
        {
            return i + 1;
        }
    }
    return -1;
}